<?php
/**
 *  物流信息
*/

namespace app\api\service;

use app\api\model\RegionCountry;
use app\api\model\WholesalOrderItem;
use app\api\model\Product as ProductMedel ;
use  app\admin\service\LogisticsRules;
use app\facade\Basic;
use app\api\model\Carts as CartsModel;
use app\api\service\CCNames as CCNamesService;
use app\admin\service\LogisticsRules as AdminServiceLogisticsRules;
use app\api\model\Address as ModelAddres;
use think\facade\Db;


class Logistics
{

    /**
     *  通过购物车获取运费
    */
    public function fee($param)
    {

        $ccNameId = null;
        if( $param['address_id'] ) {
            $addres = ModelAddres::where('id',$param['address_id'])->find();
            $ccNameId = $addres->country_id;
        }

        $warehouse_id = null;
        $product_list = [];
        $pids = array_column($param['product'],'id');
        $productInfo = ProductMedel::where('id','in',$pids)->field('id,billing_weight,free_shipping,apply_rules')->select()->toArray();
        $productInfo = array_column($productInfo,null,'id');
        foreach ($param['product'] as $k=>$p){
            $product_list[$k]['id'] = $p['id'];
            $product_list[$k]['wid'] = $p['wid'];
            $product_list[$k]['billing_weight'] = $productInfo[$p['id']]['billing_weight'] ?? '';
            $product_list[$k]['free_shipping'] = $productInfo[$p['id']]['free_shipping'] ==0 ? false:true;
            $product_list[$k]['apply_rules'] = $productInfo[$p['id']]['apply_rules']  ==0 ? false:true;
            $product_list[$k]['num'] = $p['quantity'];
        }
        $from_param['to_nation']  = $ccNameId;                 // 收货国家
        $from_param['terms']  = $param['terms'];
        $from_param['prescription']  = $param['prescription'];
        $from_param['product_list']  = $product_list;             // 商品信息

       $ServiceLogisticsRules = new AdminServiceLogisticsRules();

       $LogisticsFee = $ServiceLogisticsRules->getLogisticsFee($from_param);

        if($LogisticsFee['code'] != 0){
            return Basic::data(1,'common.errorObtainingShippingFee');
        }

        $fee = $LogisticsFee['data'];

        return Basic::data(0,'common.success',$fee);

    }

    /**
     *  通过购物车获取运费
     */
    public function shippingMethod($param)
    {
        $method = [['lable'=>'DDU','value'=>2]];
        $ccNameId = null;
        if( $param['address_id'] ) {
            $addres = ModelAddres::where('id',$param['address_id'])->find();
            $ccNameId = $addres->country_id;
        }
        $isAll = true;
        $isDdp = true;
        foreach ($param['product'] as $k=>$p){
           $rules =  \app\api\model\LogisticsRules::where(
               [
                   'to_nation' =>$ccNameId,
                   'shipping_warehouse' =>$p['wid'],
                   'prescription' => $param['prescription'],
                    'status' => 1,
                    'is_del' => 0
               ]
           )->where('execution_date', '<=', date('Y-m-d H:i:s'))->select()->toArray();
            if($rules){
               $rule_method = array_values(array_unique(array_column($rules,'terms')));

               if($rule_method != [1,2]){
                   $isAll = false;
               }
               if(!in_array(1,$rule_method)){
                   $isDdp = false;
               }
            }else{
                $isAll = false;
                $isDdp = false;
            }
        }

        if($isDdp){
            $method = [['lable'=>'DDP','value'=>1]];
        }
        if($isAll){
            $method = [['lable'=>'DDP','value'=>1],['lable'=>'DDU','value'=>2]];
        }
        return Basic::data(0,'common.success',$method);

    }

    /**
     *  通过订单明细获取运费
    */
    public function orderFee($param)
    {
        if(!isset($param['product']) || empty($param['product'])){
            return Basic::data(1,'common.errorObtainingShippingParam');
        }
        $ip = getClientIP();
        $ccNamesService = new CCNamesService();
        $ccNameId = $ccNamesService->getCCNamesByIp($ip);
        $to_param = [];
        $to_param['to_nation'] = $ccNameId;
        $to_param['prescription'] = $param['prescription'];
        $to_param['terms'] = $param['terms'];
        $to_param['product_list'] = [];
        $pids = array_column($param['product'],'id');
        $productInfo = Product::where('id','in',$pids)->field('id,billing_weight,free_shipping,apply_rules')->select()->toArray();
        $productInfo = array_column($productInfo,null,'id');
        foreach ($param['product'] as &$p){
            $p['billing_weight'] = $productInfo[$p['id']]['billing_weight'] ?? '';
            $p['free_shipping'] = $productInfo[$p['id']]['free_shipping'] ==0 ? false:true;
            $p['apply_rules'] = $productInfo[$p['id']]['apply_rules']  ==0 ? false:true;
            $p['num'] = $p['quantity'];
        }
        $to_param['product_list'] = $param['product'];
        $fee = (new LogisticsRules())->getLogisticsFee($to_param);
        $result = ['logistics_fee'=>0];
        if(isset($fee['code']) && $fee['code'] == 0 ){
            $result = $fee['data'];
        }
        return Basic::data(0,'common.success',$result);

    }

    /**
     *  获取商品运费
     */
    public function getLogisticsFee($data,$param)
    {

        $country_id = null;
        if( $param['address_id'] ) {
            $addres = ModelAddres::where('id',$param['address_id'])->find();
            $country_id = $addres->country_id;
        }

        $warehouse_id = null;
        $product_list = [];
        $amount = 0;
        $total_amount = 0;

        foreach($data as $key=>$value) {
            $product_list[$key]['id'] = $value['productid'];
            $product_list[$key]['number'] = $value['pay_quantity'];
            $warehouse_id = $value['wid'];
        }

        $from_param['shipping_warehouse']  = $warehouse_id;        // 发货仓库ID
        $from_param['to_nation']  = $country_id;                 // 收货国家
        $from_param['terms']  = $param['delivery_terms'];
        $from_param['prescription']  = $param['prescription'];
        $from_param['product_list']  = $product_list;             // 商品信息


        $ServiceLogisticsRules = new AdminServiceLogisticsRules();

        $LogisticsFee = $ServiceLogisticsRules->getLogisticsFee($from_param);


        if($LogisticsFee['code'] != 0){
            return Basic::data(1,'common.errorObtainingShippingFee');
        }

        $fee = 0.00;
        if ( $LogisticsFee['code'] == 0 ) {
            $fee = $LogisticsFee['data'];
        }

        return $fee;

    }

}
